<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投诉编辑 - 见闻间后台管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/theme-chalk/index.css">
    <script src="/install/js/vue2.6.11.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/index.js"></script>
    <script src="/install/js/axios.min.js"></script>
    <script>
        // 从URL获取参数
        function getUrlParam(name) {
            const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
            const r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
        
        // 设置axios请求拦截器，确保所有请求都包含token
        axios.interceptors.request.use(
            config => {
                // 从localStorage或sessionStorage获取token
                const token = localStorage.getItem('token') || sessionStorage.getItem('token');
                console.log('从localStorage/sessionStorage获取token:', token);
                
                // 如果token存在，则添加到请求头
                if (token) {
                    config.headers['Authorization'] = 'Bearer ' + token;
                    console.log('已添加Authorization请求头:', config.headers['Authorization']);
                } else {
                    // 尝试从cookie中获取token
                    const tokenFromCookie = getCookie('token') || getCookie('admin_token') || getCookie('Authorization');
                    console.log('从cookie获取token:', tokenFromCookie);
                    if (tokenFromCookie) {
                        config.headers['Authorization'] = 'Bearer ' + tokenFromCookie;
                        console.log('已从cookie添加Authorization请求头:', config.headers['Authorization']);
                    } else {
                        console.warn('未找到token，请求可能会失败');
                    }
                }
                
                // 打印请求URL和请求头信息用于调试
                console.log('请求URL:', config.url);
                console.log('完整请求头:', config.headers);
                
                return config;
            },
            error => {
                console.error('请求拦截器错误:', error);
                return Promise.reject(error);
            }
        );
        
        // 从cookie中获取值的辅助函数
        function getCookie(name) {
            const value = '; ' + document.cookie;
            const parts = value.split('; ' + name + '=');
            if (parts.length === 2) return parts.pop().split(';').shift();
        }
    </script>
</head>
<body>
    <div id="app" class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>{{ isEdit ? '投诉编辑' : '新建投诉' }}</span>
                <el-button 
                    type="primary" 
                    size="small" 
                    style="float: right; margin-top: -5px;"
                    @click="save"
                >
                    保存
                </el-button>
            </div>
            
            <el-form 
                ref="form" 
                :model="formData" 
                label-width="100px"
                :rules="rules"
            >
                <!-- 举报ID -->
                <el-form-item label="举报ID" v-if="isEdit">
                    <el-input v-model="formData.id" disabled></el-input>
                </el-form-item>
                
                <!-- 被举报文章信息 -->
                <el-form-item label="被举报文章" prop="article_id">
                    <div v-if="formData.article" class="article-info">
                        <div class="article-title">{{ formData.article.title || '-' }}</div>
                        <div class="article-meta">
                            作者：{{ formData.user.name || '未知' }} | 
                            发布时间：{{ formData.article.create_time || '-' }} | 
                            文章ID：{{ formData.article.id }}
                        </div>
<!--                        <el-button -->
<!--                            type="text" -->
<!--                            @click="viewArticle"-->
<!--                            size="small"-->
<!--                        >-->
<!--                            查看文章-->
<!--                        </el-button>-->
                    </div>
                    <el-input v-else v-model="formData.article_id" placeholder="请输入文章ID" v-if="!isEdit"></el-input>
                </el-form-item>
                
                <!-- 举报用户信息 -->
                <el-form-item label="举报用户">
                    <div v-if="formData.user" class="user-info">
                        用户名：{{ formData.user.name || '-' }} | 
                        用户ID：{{ formData.user.id }}
                    </div>
                    <el-input v-else v-model="formData.user_id" placeholder="请输入用户ID" v-if="!isEdit"></el-input>
                </el-form-item>
                
                <!-- 举报原因 -->
                <el-form-item label="举报原因" prop="reason">
                    <el-input 
                        v-model="formData.reason" 
                        type="textarea" 
                        :rows="4" 
                        placeholder="请输入举报原因"
                        disabled=true
                    ></el-input>
                </el-form-item>
                
                <!-- 审核状态 -->
                <el-form-item label="审核状态" prop="status">
                    <el-select 
                        v-model="formData.status" 
                        placeholder="请选择审核状态"
                        :disabled="viewOnly"
                    >
                        <el-option 
                            v-for="option in statusOptions" 
                            :key="option.value" 
                            :label="option.label" 
                            :value="option.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                
                <!-- 处理操作 -->
                <!-- <el-form-item label="处理操作" prop="action_type">
                    <el-select 
                        v-model="formData.action_type" 
                        placeholder="请选择处理操作"
                        :disabled="viewOnly"
                    >
                        <el-option 
                            v-for="option in actionOptions" 
                            :key="option.value" 
                            :label="option.label" 
                            :value="option.value"
                        ></el-option>
                    </el-select>
                    <div class="el-form-item__help">选择隐藏文章将使文章不可见但保留数据，删除文章将永久移除数据</div>
                </el-form-item> -->
                
                <!-- 处理备注 -->
                <el-form-item label="处理备注" prop="process_remark">
                    <el-input 
                        v-model="formData.process_remark" 
                        type="textarea" 
                        :rows="3" 
                        placeholder="请输入处理备注"
                        :disabled="viewOnly"
                    ></el-input>
                </el-form-item>
                
                <!-- 处理时间 -->
                <el-form-item label="处理时间" v-if="formData.process_time">
                    <el-input v-model="formData.process_time" disabled></el-input>
                </el-form-item>
                
                <!-- 处理人 -->
                <el-form-item label="处理人" v-if="formData.process_by">
                    <el-input v-model="formData.process_by" disabled></el-input>
                </el-form-item>
                
                <!-- 创建时间 -->
                <el-form-item label="创建时间" v-if="formData.create_time">
                    <el-input v-model="formData.create_time" disabled></el-input>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
    
    <style>
        .app-container {
            padding: 20px;
        }
        .article-info {
            background-color: #f5f7fa;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #ebeef5;
        }
        .article-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #303133;
        }
        .article-meta {
            font-size: 12px;
            color: #606266;
            margin-bottom: 10px;
        }
        .user-info {
            background-color: #f5f7fa;
            padding: 10px 15px;
            border-radius: 4px;
            border: 1px solid #ebeef5;
            font-size: 14px;
        }
    </style>
    
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    formData: {
                        id: '',
                        article_id: '',
                        user_id: '',
                        article: {},
                        user: {},
                        reason: '',
                        status: 0,
                        // action_type: '',
                        process_remark: '',
                        process_time: '',
                        process_by: '',
                        create_time: ''
                    },
                    statusOptions: [],
                    actionOptions: [],
                    isEdit: false,
                    viewOnly: false,
                    reportId: null,
                    rules: {
                        article_id: [
                            { required: true, message: '请输入文章ID', trigger: 'blur' }
                        ],
                        user_id: [
                            { required: true, message: '请输入用户ID', trigger: 'blur' }
                        ],
                        reason: [
                            { required: true, message: '请输入举报原因', trigger: 'blur' }
                        ],
                        status: [
                            { required: true, message: '请选择审核状态', trigger: 'change' }
                        ]
                    }
                };
            },
            created() {
                // 获取URL参数
                const urlParams = new URLSearchParams(window.location.search);
                this.reportId = urlParams.get('id');
                this.isEdit = !!this.reportId;
                console.log('页面初始化 - reportId:', this.reportId, 'isEdit:', this.isEdit);
                // 检查是否为只读模式
                this.viewOnly = !!urlParams.get('view');
                // 初始化数据
                this.initData();
            },
            methods: {
                initData() {
                    // 获取选项数据
                    this.fetchOptions();
                    
                    // 如果是编辑模式，获取举报详情
                    if (this.isEdit) {
                        this.fetchReportDetail();
                    }
                },
                fetchOptions() {
                    // 状态选项
                    this.statusOptions = [
                        {value: 0, label: '待处理'},
                        {value: 1, label: '已处理'},
                        {value: 2, label: '驳回'}
                    ];
                    
                    // 操作选项
                    this.actionOptions = [
                        {value: '', label: '无操作'},
                        {value: 'hide', label: '隐藏文章'},
                        {value: 'delete', label: '删除文章'}
                    ];
                },
                fetchReportDetail() {
                    console.log('fetchReportDetail开始执行');
                    console.log('reportId:', this.reportId);
                    console.log('请求URL:', `/admin/science.report/detail?id=${this.reportId}`);
                    
                    axios.get(`/admin/science.report/detail?id=${this.reportId}`)
                        .then(response => {
                            console.log('API响应完整数据:', response);
                            console.log('响应状态码:', response.status);
                            console.log('响应数据:', response.data);
                            
                            if (response.data && response.data.code === 200) {
                                // 获取响应数据
                                const data = response.data.data;
                                console.log('data对象结构:', data);
                                console.log('data.article类型:', typeof data.article);
                                console.log('data.user类型:', typeof data.user);
                                
                                // 确保article和user字段始终是对象，避免覆盖为空
                                const safeData = {
                                    ...data,
                                    article: data.article || {},
                                    user: data.user || {}
                                };
                                
                                console.log('safeData处理后:', safeData);
                                
                                // 合并数据
                                this.formData = Object.assign({}, this.formData, safeData);
                                console.log('合并后formData:', this.formData);
                                console.log('合并后formData.article:', this.formData.article);
                                console.log('合并后formData.user:', this.formData.user);
                            } else {
                                console.error('API返回错误:', response.data);
                                this.$message.error(response.data?.msg || '获取数据失败');
                            }
                        })
                        .catch(error => {
                            console.error('请求异常:', error);
                            console.error('错误详情:', error.response || error);
                            this.$message.error('获取数据失败，请重试');
                        });
                },
                viewArticle() {
                    if (this.formData.article && this.formData.article.id) {
                        window.open(`/admin/science.science/edit?id=${this.formData.article.id}`, '_blank');
                    }
                },
                save() {
                    this.$refs.form.validate((valid) => {
                        if (valid) {
                            // 准备提交数据
                            const submitData = {
                                ...this.formData,
                                article_id: this.formData.article?.id || this.formData.article_id,
                                user_id: this.formData.user?.id || this.formData.user_id
                            };
                            
                            // 移除不需要提交的字段
                            delete submitData.article;
                            delete submitData.user;
                            
                            // 提交请求
                            axios.post(`/science/api/report/update?id=${this.formData.id || ''}`, submitData)
                                .then(response => {
                                    if (response.data.code === 200) {
                                        this.$message.success(response.data.msg);
                                        setTimeout(() => {
                                            window.location.href = '/super#/science/report/index';
                                        }, 1500);
                                    } else {
                                        this.$message.error(response.data.msg);
                                    }
                                })
                                .catch(error => {
                                    this.$message.error('保存失败，请重试');
                                    console.error('保存失败:', error);
                                });
                        }
                    });
                }
            }
        });
    </script>
</body>
</html>